package com.android.nodejs.livejs.activities;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.util.List;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.android.nodejs.livejs.MyApplication;
import com.android.nodejs.livejs.R;
import com.android.nodejs.livejs.adapters.MessageAdapter;
import com.android.nodejs.livejs.base.BaseFragment;
import com.android.nodejs.livejs.constants.AddMessageConstants;
import com.android.nodejs.livejs.models.MyMessage;

public class MessageFragment extends BaseFragment {

    private ListView mListView;
    private View mView;
    private int numSelectedInListView;
    
    private BufferedWriter w;
    private MessageAdapter messageAdapter;

    @Override
    public void inits() {
        // nothing
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_messages, null);
         IntentFilter filterMessageChat = new IntentFilter("HAVE_READ_MESSAGE");
         getActivity().registerReceiver(new MessageBroadCastReceiver(), filterMessageChat);
        return mView;
    }

    @Override
    public void initComponents(View view) {
        w = new BufferedWriter(new OutputStreamWriter(MyApplication.OS_CURRENT));
        mListView = (ListView) view.findViewById(R.id.listMessages);
        messageAdapter = new MessageAdapter(getActivity(), MyApplication.LIST_MESSAGE_OFFLINE);
        mListView.setAdapter(messageAdapter);
        mListView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
                numSelectedInListView = position;
                List<String> m = MyApplication.LIST_MESSAGE_OFFLINE.get(position).getMessage();
                String displayMsg = "";
                for(int i=0; i<m.size(); i++) {
                    displayMsg += m.get(i);
                    if(i != (m.size()-1)) {
                        displayMsg += "\n";
                    }
                }
                // show dialog
                AlertDialog.Builder bui = new AlertDialog.Builder(getActivity()).setMessage(displayMsg).setTitle("Message content")
                        .setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // set have read this message
                                try {
                                    w.write(AddMessageConstants.SET_HAVE_READ_MESSAGE);
                                    w.write(MyApplication.USER_CURRENT.getId() + "!!"
                                            + MyApplication.LIST_MESSAGE_OFFLINE.get(numSelectedInListView).getIdGroup());
                                    w.flush();
                                } catch (IOException e) {
                                    Log.d("IOException", e.getClass().getSimpleName() + ": " + e.getMessage());
                                    e.printStackTrace();
                                }
                            }
                        }).setNegativeButton("Chat", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // set have read this message
                                try {
                                    w.write(AddMessageConstants.SET_HAVE_READ_MESSAGE);
                                    w.write(MyApplication.USER_CURRENT.getId() + "!!"
                                            + MyApplication.LIST_MESSAGE_OFFLINE.get(numSelectedInListView).getIdGroup());
                                    w.flush();
                                } catch (IOException e) {
                                    Log.d("IOException", e.getClass().getSimpleName() + ": " + e.getMessage());
                                    e.printStackTrace();
                                }
                                
                                Intent intentChat = new Intent();
                                intentChat.setClass(getActivity(), ChatActivity.class);
                                Bundle b = new Bundle();
                                b.putSerializable("list_msgs", (Serializable) (MyApplication.LIST_MESSAGE_OFFLINE.get(numSelectedInListView).getMessage()));
                                b.putSerializable("list_times", (Serializable) (MyApplication.LIST_MESSAGE_OFFLINE.get(numSelectedInListView).getTime()));
                                b.putInt("group_id",  ((MyMessage) MyApplication.LIST_MESSAGE_OFFLINE.get(numSelectedInListView)).getIdGroup());
                                b.putInt("sender_id",  ((MyMessage) mListView.getAdapter().getItem(numSelectedInListView)).getIdSender());
                                b.putString("friend_full_name",  ((MyMessage) mListView.getAdapter().getItem(numSelectedInListView)).getNameSender());
                                b.putString("friend_avatar",  ((MyMessage) mListView.getAdapter().getItem(numSelectedInListView)).getAvatarSender());
                                intentChat.putExtras(b);
                                getActivity().startActivityForResult(intentChat, 101);
                            }
                        });
                bui.create();
                bui.show();
            }
        });
    }

    @Override
    public void addListenners() {
        // nothing
    }
    
    /** Show Toast message */
    private Handler toastHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                MyApplication.LIST_MESSAGE_OFFLINE.remove(numSelectedInListView);
                mListView.setAdapter(messageAdapter);
            }
        }
    };

    /**
     * receive message broadcast
     * 
     * @author vuvt
     * 
     **/
    private class MessageBroadCastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ("HAVE_READ_MESSAGE".equals(intent.getAction())) {
                int num = Integer.parseInt(intent.getStringExtra("msg"));
                Message msg = toastHandler.obtainMessage(num);
                toastHandler.sendMessage(msg);
            }
        }
    }
     

}
